<?php

namespace app\common\controller;

use app\common\exception\MiException;
use app\common\service\CommonOrderRefundService;
use app\common\service\CommonOrderService;
use app\common\service\CommonSiteConfigService;
use app\common\service\CommonStoreManagerService;
use app\common\service\pay\WxpayService;
use app\model\store\Order;
use app\model\store\OrderRefund;
use app\model\store\StoreManager;
use JetBrains\PhpStorm\NoReturn;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Log;
use think\response\Json;

class PublicController
{

    /***
     *
     * 订单微信支付回调
     * @throws MiException
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function wxPayNotify($id):Json
    {
        $config = CommonSiteConfigService::instance()->getWxPayConfig((int)$id);
        $params = WxpayService::getInstance($config)->notify();
        // 验证订单
        $amount = $params['amount']['payer_total'] / 100;
        $order = Order::with(['items'])->where('order_no', $params['out_trade_no'])->where('pay_price', $amount)->find();
        if (!$order) {
            Log::error("----订单验证失败------");
            throw new MiException("订单验证失败");
        }

        // 如果订单未支付，修改订单状态为已支付
        if ($order->order_status == 'unpaid') {
            CommonOrderService::instance()->paySuccess('wx', $order, $params);
        }

        return \json([
            'code' => 'SUCCESS',
        ]);
    }


    /**
     * 订单退款通知
     * @throws DataNotFoundException
     * @throws MiException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    public function wxRefundNotify($id): Json
    {
        $config = CommonSiteConfigService::instance()->getWxPayConfig((int)$id);
        $params = WxpayService::getInstance($config)->notify();
        // 验证订单
        $amount = $params['amount']['payer_refund'] / 100;
        $orderRefund = OrderRefund::with(['items'])->where('order_refund_no', $params['out_refund_no'])->where('refund_price', $amount)->find();
        if (!$orderRefund) {
            Log::error("----退款单验证失败------");
            throw new MiException("退款单验证失败");
        }
        // 退款成功的操作
        CommonOrderRefundService::instance()->refundSuccess($orderRefund, $params);

        return \json([
            'code' => 'SUCCESS',
        ]);
    }

    /**
     * 申请店长付款通知
     * @param $id
     * @return Json
     * @throws DataNotFoundException
     * @throws DbException
     * @throws MiException
     * @throws ModelNotFoundException
     */
    public function wxPayNotifyStoreManager($id): Json
    {
        $config = CommonSiteConfigService::instance()->getWxPayConfig((int)$id);
        $params = WxpayService::getInstance($config)->notify();
        // 验证订单
        $amount = $params['amount']['payer_total'] / 100;
        $manager = StoreManager::where('order_no', $params['out_trade_no'])->find();
        if (!$manager) {
            Log::error("----申请店长付款验证失败------");
            throw new MiException("申请店长付款验证失败");
        }

        // 成功的操作
        $manager->pay_order_no = $params['transaction_id'];
        $manager->pay_time = $params['success_time'];
        $manager->save();

        return \json([
            'code' => 'SUCCESS',
        ]);
    }


    //

    /**
     * 计划任务：每月15号释放上月店长佣金
     * @throws DbException
     */
    #[NoReturn] public function distRewardJob(){
        $time = time();
        // 上个月的日期
        $lastMonthDate = date('Y-m', strtotime("-1 month", $time));
        CommonStoreManagerService::instance()->freeStoreManagerPrice($lastMonthDate);
        exit("success");
    }
}
